package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component

public class SimpleRedisLock {
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    public static String UUID = cn.hutool.core.lang.UUID.randomUUID().toString()+"-";

    public boolean tyrLock(String lockName, long timeout, TimeUnit timeUnit){
        String threadId = String.valueOf(Thread.currentThread().getId())+UUID;
        Boolean b = redisTemplate.opsForValue().setIfAbsent("lock:" + lockName, threadId, timeout, timeUnit);
        return b;
    }
    public void unLock(String lockName){
        String threadId = String.valueOf(Thread.currentThread().getId())+UUID;
        String s = redisTemplate.opsForValue().get("lock:" + lockName);
        if(s.equals(threadId)){
            redisTemplate.delete("lock"+lockName);
        }
    }
}
